package purchase

import (
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

/*
*冷库
 */
func storage(r *gin.RouterGroup) {
	//冷库费用

	coldStore := r.Group("/storage")
	{
		//冷库
		coldStore.POST(sql.RequestAdd, storageAdd)
		coldStore.POST(sql.RequestUpdate, storageUpdates)
		coldStore.GET(sql.RequestData, storageData)
		coldStore.GET(sql.RequestList, storageList)
		coldStore.GET(sql.RequestDelete, storageDelete)

		//冷库费用
		fee := coldStore.Group("/fee")
		{
			fee.POST(sql.RequestAdd, feeAdd)
			fee.POST(sql.RequestUpdate, feeUpdates)
			fee.GET(sql.RequestData, feeData)
			fee.GET(sql.RequestList, feeList)
			fee.GET(sql.RequestDelete, feeDelete)
		}
	}
}

// ===========冷库===========
func storageAdd(c *gin.Context) {
	sql.HttpAdd(c, &model.ColdStorage{}, nil)
}

func storageUpdates(c *gin.Context) {
	sql.HttpUpdates(c, &model.ColdStorage{}, nil)
}

func storageDelete(c *gin.Context) {
	sql.HttpDeleteById(c, &model.ColdStorage{})
}

func storageData(c *gin.Context) {
	sql.HttpData(c, &model.ColdStorage{}, func(db *gorm.DB) *gorm.DB {
		if coldStore := c.Query("storage"); coldStore != "" {
			db = db.Where("storage = ?", coldStore)
		} else {
			db.Error = errors.New(sql.ErrorParams)
		}
		return db
	})
}

func storageList(c *gin.Context) {
	sql.HttpList(c, &[]model.ColdStorage{}, func(db *gorm.DB) *gorm.DB {
		if city := c.Query("city"); city != "" {
			db = db.Where("city = ?", city)
		}
		return db
	})
}

// ===========仓储费===========
func feeAdd(c *gin.Context) {
	sql.HttpAdd(c, &model.StorageFee{}, nil)
}

func feeUpdates(c *gin.Context) {
	sql.HttpUpdates(c, &model.StorageFee{}, nil)
}

func feeDelete(c *gin.Context) {
	sql.HttpDeleteById(c, &model.StorageFee{})
}

func feeList(c *gin.Context) {
	sql.HttpList(c, &[]model.StorageFee{}, func(db *gorm.DB) *gorm.DB {
		if containerNo := c.Query("containerNo"); containerNo != "" {
			db = db.Where("container_no = ?", containerNo)
		} else {
			db.Error = errors.New(sql.ErrorParams)
		}
		return db
	})
}

func feeData(c *gin.Context) {
	sql.HttpData(c, &model.StorageFee{}, func(db *gorm.DB) *gorm.DB {
		if coldStore := c.Query("storage"); coldStore != "" {
			db = db.Where("storage = ?", coldStore)
		} else {
			db.Error = errors.New(sql.ErrorParams)
		}
		return db
	})
}
